<?php
namespace Wx\Controller;

use Think\Controller;

class ShopController extends BaseController
{
    /**
     * 搜索店铺
     * @return [type] [description]
     */
    public function getShop()
    {
        $m = D('Search');
        session('lat', I('lat'));
        session('lon', I('lon'));
        session(array('name' => 'lon', 'expire' => 86400));
        session(array('name' => 'lon', 'expire' => 86400));

        $shopList = $m->getShop();
        $this->ajaxReturn($shopList);
    }

    /**
     * 新店来袭
     */
    public function newShop()
    {
        //图片轮播
        $db = M('ads');
        $date = date('Y-m-d', time());
        $where['adPositionId'] = '3';
        $where['_string'] = " '$date' between  adStartDate  and  adEndDate";
        $adInfo = $db->where($where)->field('adId,adfile,adurl')->order('adSort ASC')->select();
        $this->assign('adInfo', $adInfo);

        //新店
        $this->shop = D('Shop')->newShops();
        // dump($this->shop);die;
        $this->display('newShop');
    }

    /**
     * 商店投诉页面
     */
    public function complaint()
    {
        $this->shopId = I('shopId');
        $this->orderId = I('orderId');
        $this->name = urldecode(I('name'));
        $this->userId = session('oto_userId');
        $this->display('complaint');
    }

    /**
     * 店铺投诉请求
     */
    public function tousu()
    {
        $phone = I('phone');
        $content = I('content');
        $user_id = I('user_id');
        $shopId = I('shopId');
        $orderId = I('orderId');
        $time = time();
        //$time=date('Y-m-d H:i:s');

        $m = M('complain');
        $map = [
            'shopId' => $shopId,
            'orderId' => $orderId,
            'userId' => $user_id,
            'isFlag' => 1,
        ];

        $suggest = $m->where($map)->find();

        if (isset($suggest)) {
            $data['pan'] = "-1";
            $data['msg'] = "您已经投诉过了";
        } else {

            $data = [
                'userId' => $user_id,
                'phone' => $phone,
                'content' => $content,
                'orderId' => $orderId,
                'shopId' => $shopId,
                'time' => $time,
            ];
            $result = $m->data($data)->add();

            if ($result) {
                $data['pan'] = "1";
                $data['msg'] = "投诉成功";
            } else {
                $data['pan'] = "-1";
                $data['msg'] = "投诉失败";
            }
        }
        $this->ajaxReturn($data);
        //echo json_encode($data);
    }

    /**
     * 店铺分类商品
     */
    public function getShopGoods()
    {
        $this->ajaxReturn(D('Shop')->getShopGoods());
    }

    /**
     * 进入商店首页
     */
    public function shop()
    {
        //session('oto_userId',null);
        if (session('oto_userId')) {

            $map = [
                'favoriteType' => 1,
                'userId' => session('oto_userId'),
                'targetId' => I('id'),
            ];
            $this->favorites = M('favorites')->where($map)->getField('favoriteId');
            $this->isLogin = 1;
        } else {
            $this->isLogin = 0;
        }

        $id = I('get.id', 0, intval);
        //店铺信息
        //'shopAtive'=>1,
        $shopInfo = M('shops')->where(array('shopId' => $id, 'shopFlag' => 1, 'shopStatus' => 1))->find();
        $this->shopAtive = $shopInfo['shopAtive']; //超管控制是否营业

        //营业时间判断
        if ($shopInfo['serviceStartTime'] && $shopInfo['serviceEndTime']) {

            $now_time = date('H', time());
            //不在营业时间内
            if ($shopInfo['serviceStartTime'] > $now_time || $shopInfo['serviceEndTime'] < $now_time) {
                $this->close = 1;

            }
        }
        $lat = session("lat");
        $lon = session("lon");
        $ptm = D("Wx/Search")->getPtDeliveryConfig();
            //计算平台配送费/配送时间
            if($shopInfo['deliveryType'] == 1 && !empty($ptm)){
                $lat2 = $shopInfo['latitude'];
                $lon2 = $shopInfo['longitude'];
                $shopInfo['juli'] = D("Wx/Search")->getDistance($lat, $lon, $lat2, $lon2);

                if($shopInfo['juli']){
                    for ($j=0; $j < count($ptm); $j++) { 
                        if($shopInfo['juli'] <= $ptm[$j]['go_distance'] * 1000){
                            $shopInfo['deliveryCostTime'] = $ptm[$j]['go_distance_time2'];
                            $shopInfo['deliveryMoney'] = $ptm[$j]['go_money'];
                            break;
                        }
                        if($j == count($ptm) - 1 && $shopInfo['juli'] > $ptm[$j]['go_distance'] * 1000){
                            $this->redirect(U('Index/index','','',0));
                            break;
                        }
                    }
                }
            }
        $this->shopInfo = $shopInfo;

        //店铺分类信息
        $shopCate = M('shops_cats')->where(array('shopId' => $id, 'catFlag' => 1, 'parentId' => 0, 'isShow' => 1))->select();
        $this->cate = $shopCate;
        //店铺评论信息
        $this->shopComment = D('Shop')->getComment();
        //购物车信息
        $cartInfo = D('Cart')->getCartInfo();

        $goods_num = 0;
        $goods_list = [];
        $totalMoney = 0;

        //print_r($cartInfo);die;
        //print_r($cartInfo['cartgoods'][$id]['shopgoods']);die;

        if ($cartInfo['cartgoods'][$id]['shopgoods']) {
            foreach ($cartInfo['cartgoods'][$id]['shopgoods'] as $value) {

                if ($value['isGroup'] == 0 && $value['isSeckill'] == 0) {
//不显示秒杀商品和团购商品
                    $value['attrId'] = '';
                    if ($value['goodsAttrId']) {
//是否属性商品
                        $num = count(explode('_', $value['goodsAttrId']));
                        $tempMoney = 0;
                        $value['attrName'] = '';
                        //属性商品价格相加
                        for ($i = 0; $i < $num; $i++) {
                            $tempMoney += $value[$i]['shopPrice'];
                            $value['attrName'] .= "【{$value[$i]['attrName']}】";
                        }
                        // $totalMoney+=$tempMoney*$value['cnt'];
                        $value['shopPrice'] = $tempMoney;
                        $value['attrId'] = implode(',', explode('_', $value['goodsAttrId']));
                    }

                    $totalMoney += $value['shopPrice'] * $value['cnt'];

                    $goods_num += $value['cnt'];
                    //$attrId = $value[0]['goodsAttrId']?$value[0]['goodsAttrId']:0;
                    $goods_list["{$value['goodsId']}_{$goodsAttrId}"] = $value;
                }

            }
        }

        //返回地址处理
        //$this->totalMoney = $cartInfo['cartgoods'][I('id')]['totalMoney'];
        $this->totalMoney = $totalMoney;
        if (I('ref')) {
            $this->ref = I('ref');
        } else if (I('goodsDetail')) {
            $this->ref = '/Wx/Index/index';
        } else {
            $this->ref = 'javascript:history.back()';
        }
        $this->number = $goods_num;
        $this->cartList = $goods_list;
        //dump($goods_list);die;
        $this->carInfo = json_encode($goods_list); //json购物车信息
        $this->display('shop');
    }

    public function unlimitedForLayer($cate, $name = 'child', $pid = 0)
    {
        $arr = array();
        $name = 'child';
        foreach ($cate as $v) {
            if ($v['parentId'] == $pid) {
                $v[$name] = self::unlimitedForLayer($cate, $name, $v['catId']);
                $arr[] = $v;
            }
        }
        return $arr;
    }
}
